<template>
    <div class="repair-store-order">

      <section class="app-main">
        <div class="product-content" v-for="item in orderList">
          <div class="product-img">
            <img :src="noneImg"/>
          </div>
          <ul class="product-details">
            <li class="item item-title">{{item.commAttribName}}</li>
            <li class="item item-price">
              ￥<span class="price">{{item.commattribPrice}}</span><span class="item-factory">{{item.factory}}</span>
              <div class="select-count">
                <span class="item item-reduce js-item-reduce" @click="handleModify(item,'reduce')">-</span>
                <input class="item item-input js-item-input" type="number" v-model="item.count"/>
                <span class="item item-add js-item-add" @click="handleModify(item,'add')">+</span>
              </div>
            </li>
          </ul>
        </div>
        <div class="module-block">
          <div class="block-header">*建议提供车架号、整车图、破损部位等图片。</div>

          <uploadOssImg v-bind:myFileLocate="'0'" @myMediaAttr="getMyMediaAttr" @getAccessToken="getAccessToken"></uploadOssImg>
        </div>
        <div class="module-block">
          <selectYuyueDate @getDateTimeYuyue="getDateTimeYuyue"></selectYuyueDate>

          <mt-cell
            title="服务方式:" class="mint-field">
            <dl class="date-list">
              <dl class="date-list service-list">
                <dd class="date-item" v-for="(item,index) in selectGoAttr" :class="{active:curIndexService==index}" @click="handleSelectService(item,index)">
                  <span class="date-title">{{item.title}}</span>
                </dd>
              </dl>
            </dl>
          </mt-cell>
          <template v-if="selectService.itemType=='4101'">
            <mt-field label="联系电话" placeholder="请输入联系电话" v-model="linkPhone" type="number"></mt-field>
            <mt-field label="作业地点" placeholder="请输入作业地点" v-model="address"><span class="iconfont icon-didian1" style="font-size: 22px;color: #26a2ff" @click="handleSelectAddress"></span></mt-field>
          </template>

          <mt-cell
          title="捎话:" class="mint-field" is-link>
          </mt-cell>
          <div class="mint-field-comments">
            <textarea v-model="comments" class="item-textarea" placeholder="给派派捎句话" oninput="this.style.height=this.scrollHeight + 'px'"></textarea>
          </div>
        </div>
        <dl class="module-block" v-if="!$route.query.class">
          <dd class="word-content" v-if="selectService.itemType=='4101'">
            上门费用：<span class="text-red pull-right" style="font-size: 13px;text-align: right;">需客服人员确认维修地点后报价</span>
          </dd>

          <!--<dd class="word-content" v-for="service in serviceAttr">-->
            <!--{{service.name}}：<span class="text-red pull-right">￥{{(service.price)*myCount}}</span>-->
          <!--</dd>-->
          <!--<dd class="word-content" v-for="item in orderList">-->
          <!--<div v-for="service in item.serviceAttr">{{service.name}}：<span class="text-red pull-right">￥{{(service.price)*item.count}}</span></div>-->
          <!--</dd>-->

          <dd class="word-content">
            商品总额：<span class="text-red pull-right">￥{{productPrice}}</span>
          </dd>
          <dd class="word-content">实付总额：<span class="text-red pull-right">￥{{getNumPrice}}</span></dd>
        </dl>
        <div class="button-content-bottom">
          <mt-button type="primary" @click.native="handleToPay">
            {{$route.query.class?'立即预约询价':'立即预约'}}
          </mt-button>
        </div>


        <!--地图弹窗-->
        <mt-popup
          v-model="popupMap"
          position="right" class="popup-map">
          <map-select @mapData="getMapData" @mapClose="handleMapClose"></map-select>
        </mt-popup>
        <!--地图弹窗-->

      </section>
    </div>
</template>

<script>
  import { Toast ,DatetimePicker,Indicator} from 'mint-ui';
  import mapSelect from '../common/map-select';
  import uploadOssImg from '../common/upload-oss-img.vue'
  import selectYuyueDate from '../common/select-yuyue-date.vue'
  export default {
    components:{
      mapSelect,
      uploadOssImg,
      selectYuyueDate
    },
    data () {
      return {
        orderList:[],
        serviceAttr:[],
        productPrice:0,
        comments:'',
        myCount:1,
        res:'',
        curIndex:-1,
        curIndexService:0,
        selectService:{title:'到店',itemType:4102},
        selectGoAttr:[{title:'到店',itemType:4102},{title:'上门',itemType:4101}],
        noneImg:'./static/img/img-none.jpg',
        accessToken:'',
        mediaAttr:[],
        myUploads:[],
        linkPhone:'',
        address:'',
        xAxis:'',
        yAxis:'',
        popupMap:false,
        allotDateYuyue:'',
        bookTimeStart:'',
        bookTimeEnd:'',
        items:[],
      }
    },
    beforeRouteEnter (to, from, next) {
      var u = navigator.userAgent;
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      // XXX: 修复iOS版微信HTML5 History兼容性问题
      if (isiOS && to.path !== location.pathname) {
        // 此处不可使用location.replace
        location.assign(to.fullPath)
      }else {
        next()
      }
    },
    mounted(){

      /**获取选择的商品信息**/

      if(this.$route.query.class){
        this.comments=this.$route.query.class
        this.carModel=this.$route.query.name+" - "+this.$route.query.class;
      }else{
        this.orderList=JSON.parse(sessionStorage.getItem('orderList'))
      }
      this.linkPhone=JSON.parse(sessionStorage.getItem('linkPhone'))
    },
    computed:{

      /**计算实付总额**/
      getNumPrice:function(){
        let total=0;
        this.productPrice=0;
        for(var i=0;i<this.orderList.length;i++){
          for(var j=0;j<this.orderList[i].serviceAttr.length;j++){
            total+=(this.orderList[i].serviceAttr[j].price)*(this.orderList[i].count)
          }
          total+=(this.orderList[i].commattribPrice)*(this.orderList[i].count)
          this.productPrice+=(this.orderList[i].commattribPrice)*(this.orderList[i].count)
        }
        return total
      },
    },
    methods:{

      /**获取accessToken**/
      getAccessToken(data){
        this.accessToken=data;
      },

      /**获取车辆维修图**/
      getMyMediaAttr(data){
        this.mediaAttr=data
      },

      /**selectYuyueDate组件获取预约时间**/
      getDateTimeYuyue(data){
        console.log(data,1111)
        this.allotDateYuyue=data.allotDateYuyue
        this.bookTimeStart=data.bookTimeStart
        this.bookTimeEnd=data.bookTimeEnd
      },
      /**选择地址**/
      handleSelectAddress(){
        this.popupMap=true;
      },
      /**修改购买数量**/
      handleModify(item,type){

        if(type=='reduce'){
          if(item.count<=1){
            Toast({
              message: '购买数量不能小于1',
              position: 'middle',
              duration:1200
            });
            return false;
          }else{
            item.count--;
          }

        }else{
          item.count++;
        }

      },

      handleSelectService(item,index){
        this.curIndexService=index;
        this.selectService=item;
      },
      /**获取oss配置**/
      getOss(){
        let OSS = require('ali-oss');
        this.client = new OSS({
          region: "oss-cn-shenzhen",
          secure: true,//https
          endpoint: 'oss-cn-shenzhen.aliyuncs.com',
          accessKeyId: "LTAIPCNdQvX5yOwc",
          accessKeySecret: "7bReGAz8bc9aJdK4IAz5KW5fnNOzrQ ",
          bucket: 'rmcbapp'
        });
      },

      /**toBuffer**/
      toBuffer(ab) {
        var buf = new Buffer(ab.byteLength);
        var view = new Uint8Array(ab);
        for (var i = 0; i < buf.length; ++i) {
          buf[i] = view[i];
        }
        return buf;
      },
      /**关闭地图**/
      handleMapClose(){
        this.popupMap=false;
      },
      /**选择地图数据**/
      getMapData(data){
        this.address=data.address;
        this.xAxis=data.xAxis;
        this.yAxis=data.yAxis;
      },

      /**整理商品和服务数据**/
     handleProductData(){

        for(var i=0;i<this.orderList.length;i++){
          let itemProduct={
            commattribId:this.orderList[i].commattribId,
            price:this.orderList[i].commattribPrice,
            amount:(this.orderList[i].commattribPrice)*(this.orderList[i].count),
            itemType:3801,
            indexNo:i+1,
            qty:this.orderList[i].count,
            commattribName:this.orderList[i].commAttribName,
            commattribCode:this.orderList[i].commAttribCode,
            commattribFactory:this.orderList[i].factory
          };
          this.items.push(itemProduct);
        }
      },
      /**点击按钮操作**/
      handleToPay(){
        if(this.allotDateYuyue==''){
          Toast({
            message: '请选择预约时间',
            position: 'middle',
            duration:1000
          });
          return false;
        }
        if(this.dateRange==''){
          Toast({
            message: '请选择预约时段',
            position: 'middle',
            duration:1000
          });
          return false;
        }
        this.handleProductData();
        this.getOss();
        var that=this;
        that.myUploads=[];
        if(that.mediaAttr.length>0){


          /**有车辆图**/
          for(var i=0;i<that.mediaAttr.length;i++){
            const mediaId = that.mediaAttr[i].serverId; // 微信多媒体文件id
            const fileLocate = that.mediaAttr[i].fileLocate; // 上传图片类型
            const tag = that.mediaAttr[i].tag; // 是否上传到标记
            if(tag==''){
              Indicator.open({
                text: '预约提交中...',
                spinnerType: 'snake'
              });

              /**通过mediaId从微信获取图片流**/
              that.$axios({
                method: 'get',
                url:'wx/cgi-bin/media/get?access_token='+that.accessToken+'&media_id='+mediaId,
                responseType:'arraybuffer',
              }).then((res)=>{
                /**arrayBuffer转Buffer**/
                var buffer = that.toBuffer(res.data);
              var destPath = 'erpDemand/'+mediaId+'.jpg'; // OSS文件路径
              var postitem={}

              /**上传到阿里云**/
              that.client.put(destPath, buffer).then((result) => {
                console.log('图片上传阿里云结果', result);
                postitem={
                  bucketName:'rmcbapp',
                  fileLocate:'',
                  fileType:0,
                  sourceFileName:mediaId+'.jpg',
                  ossPath:result.name,
                  ossKey:'rmcbapp/'+result.name,
                  etag:result.res.headers.etag
                };
                that.myUploads.push(postitem);
                  if(that.myUploads.length==i){
                    this.bookingApi();
                  }

                }).catch((err) => {
                    console.log(err)
                  Toast({
                    message: '图片上传失败',
                    position: 'middle',
                    duration:1000
                  });
                });
              })
              }else{
                console.log('该图片已上传')
              }
          };
          }else{
            /**没有车辆图**/
            Indicator.open({
              text: '预约提交中...',
              spinnerType: 'snake'
            });
            this.bookingApi();
        }
      },
      /**和后台交互接口**/
      bookingApi(){

          var params = new URLSearchParams();

        /**判断是询价还是报修**/
          if(this.$route.query.class){
            var postData={
              shopId:'1000001',
              demandType:'4601',
              carModel:this.$route.query.name,
              uploads:this.myUploads,
              bookTimeStart:this.bookTimeStart,
              bookTimeEnd:this.bookTimeEnd,
              linkPhone:this.linkPhone,
              linkAddress:this.address,
              xAxis:this.xAxis,
              yAxis:this.yAxis,
              remark:this.comments,
              serviceType:this.selectService.itemType
            }
          }else{
            var postData={
              carModelId:this.orderList[0].carModelId,
              carModel:this.orderList[0].carModel,
              shopId:'1000001',
              demandType:'4601',
              uploads:this.myUploads,
              bookTimeStart:this.bookTimeStart,
              bookTimeEnd:this.bookTimeEnd,
              linkPhone:this.linkPhone,
              linkAddress:this.address,
              xAxis:this.xAxis,
              yAxis:this.yAxis,
              amount:this.getNumPrice,
              grossProceeds:this.getNumPrice,
              items:this.items,
              remark:this.comments,
              serviceType:this.selectService.itemType
            };
          }

          params.append('demandData',JSON.stringify(postData));
          this.$axios({
            method: 'post',
            url:'gp/app/bookingOrderApp!saveBooking.do',
            data:params
          }).then((res)=>{
            if(res.data.result==true &&　res.data.statusCode==200){
                Indicator.close();
                Toast({
                  message: '预约提交成功',
                  position: 'middle',
                  duration:1200
                });
                setTimeout(()=>{
                  this.$router.push({path:'/report-order-list'})
              },1200)
            }else{
              Indicator.close();
              Toast({
                message: res.data.message,
                position: 'middle',
                duration:1000
              });
            }
          }).catch((error)=> {
              Indicator.close();
            Toast({
              message: error,
              position: 'middle',
              duration:2000
            });
          });
      }
    }
  }
</script>

<style>

  .repair-store-order .app-main{
    padding:0 0 52px;
  }
  .repair-store-order .item-textarea{
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    height: 80px;
    border-radius: 0;
    border: 0;
    outline: 0;
    padding:4px 10px;
    font-size: 15px;
    width: 100%;
    box-shadow: 1px 1px 6px 2px rgba(0,0,0,0.08) inset;
  }
  .repair-store-order .date-list {
    display: inline-block;
    width: 100%;
    background: #fff;
    margin: 0 -6px;
    font-size: 0;
    text-align: left;
  }
  .repair-store-order .date-item {
    display: inline-block;
    width:49%;
    padding: 0 6px;
    margin: 0 0 12px; }
  .repair-store-order .service-list .date-item{
    margin: 0;
  }

  .repair-store-order .date-item.active .date-title {
    background: none;
    border: 1px solid #26a2ff;
    color: #26a2ff; }
  .repair-store-order .service-list .date-item.active .date-title {
    background: #26a2ff;
    color: #fff; }
  .repair-store-order .date-item .date-title {
    background: #f6f8fa;
    display: block;
    padding:8px;
    border-radius: 4px;
    font-size: 14px;
    text-align: center;
    border: 1px solid #f6f8fa; }

  .repair-store-order .mint-field .mint-cell-wrapper{
    border-bottom:1px solid #eee;
    background:none;
    padding:10px;
    font-size: 15px;
    color: #666;

  }

  .repair-store-order .mint-field .mint-cell-value{
    text-align: right;
  }
  .repair-store-order .mint-field .mint-field-core{
    padding-left: 16px;
  }
  .repair-store-order .mint-checkbox-input:checked+.mint-checkbox-core{
    background-color: red;
    border-color: red;
  }
  .repair-store-order .mint-checkbox-label{
    font-size: 14px;
    color:#666;
  }
  .repair-store-order .product-content{
    background: #fff;
    margin:0 0 12px;
    padding: 12px;
    font-size:14px;
  }
  .repair-store-order .product-content .product-img{
    display: table-cell;
    vertical-align: top;
    padding-right: 12px;
    width: 32%;
  }
  .repair-store-order .product-content .product-img img{
    width: 100px;
    height: 100px;
  }
  .repair-store-order .product-content .product-details{
    position: relative;
    display: table-cell;
    vertical-align: top;
    width: 68%;
  }
  .repair-store-order .product-content .item{
    margin:0 0 4px;
  }
  .repair-store-order .product-content .item-title{
    font-size: 15px;
    color: #000;
    margin:0 0 6px;
    line-height: 22px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp:2;
    overflow: hidden;

  }
  .repair-store-order .product-content .item-price{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding:12px 0 0;
    color: red;
    font-size: 16px;
  }

  .repair-store-order .module-block{
    background: #fff;
    margin:0 0 12px;
  }
  .repair-store-order .word-content{
    background: #fff;
    padding:14px 12px;
    font-size: 15px;
    color:#666;
    margin: 0;
    line-height: 20px;
    border-top:1px solid #f5f5f5;
    overflow: hidden;
  }

  .repair-store-order .block-header{
    background-color:#f5f5f5;
    position: relative;
    display: block;
    padding:10px 12px 10px;
    font-size:14px;
  }
  .repair-store-order .block-header:before{
    background:#26a2ff;
    position: relative;
    top:-2px;
    display:inline-block;
    vertical-align: middle;
    width:2px;
    height:16px;
    content: '';
    margin-right:5px;
  }

  .repair-store-order .pic-car .mint-swipe-items-wrap{
    height: 100px;
  }
  .repair-store-order .pic-car .mint-swipe-indicators{
    display: none;
  }

  .repair-store-order .select-count {
    float: right;
    display: inline-block;
    border: 1px solid #eee;
    border-radius: 5px;
  }
  .repair-store-order .select-count .item {
    display: inline-block;
    vertical-align: middle;
    width:30px;
    height:28px;
    font-size:16px;
    text-align: center;
    font-weight: bold;
    line-height: 22px;
    margin: 0;
  }
  .repair-store-order .select-count .item-reduce {
    font-size: 20px;
    color: #0080e5;
    border-right: 1px solid #eee; }
  .repair-store-order .select-count .item-add {
    font-size:20px;
    color: #0080e5;
    border-left: 1px solid #eee;
  }
  .repair-store-order .select-count .item-input {
    width:32px;
    outline: none;
    border: none;
    font-weight: normal;}
  .repair-store-order .item-factory{
    border: 1px solid red;
    margin-left: 8px;
    padding:0 4px;
    border-radius: 3px;
    font-size: 12px;
    letter-spacing:1px;
  }
  .repair-store-order .popup-map{
    width: 100%;
    height: 100%;
  }
  .repair-store-order .button-content-bottom{
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: #fff;
    display: flex;
    box-shadow: 0px -6px 4px 0px rgba(0, 0, 0, 0.03);
  }
  .repair-store-order .button-content-bottom .mint-button{
    display: flex;
    flex: 1;
    border-radius: 0;
    justify-content: center;
    font-size: 16px;
    box-shadow: none;
    height: 50px;

  }
  .mint-field-comments{
    padding:12px;
  }
  .mint-field-comments .mint-cell{
    display: inline-block;
    width: 33.2%;
  }
</style>
